import json
import pickle
import random
import threading

from PySide6.QtCore import Qt
from PySide6.QtWidgets import QTableWidgetItem

from bytedance import Bytedance
from ikuai import IKuai
from utils import *
import time


# 魔云腾安卓容器API
class AndroidDocker:
    def __init__(self, server_ips):
        # ip数组要求格式：ip:端口
        self.server_ips = server_ips
        # # 超级SDK接口地址
        self.api = HttpApi("http://127.0.0.1:5000")
        # 安卓ip字典
        self.android_list = {}
        self.l2tp = {}

        DkGlobal().android_docker = self

    def start_android(self):
        win_log("初始化....")
        self.iKuai = IKuai()
        # 获取设备信息
        self.get_android_list()

        # self.android_list.values()
        self.save_android_list_to_json()
        # 保持Ikuai
        # ikuai_thread = threading.Thread(target=self.iKuai.latp_keep)
        # ikuai_thread.start()
        # 初始化IKuai
        # 获取设备列表
        threads = []
        stop_events = []
        while DkGlobal().window.running:
            if DkGlobal().body.bodyRunning:
                for android in self.android_list.values():
                    if (android['status'] == "wait" and android['switch'] == True):
                        stop_event = threading.Event()
                        thread = threading.Thread(target=self.start, args=(android, stop_event))
                        threads.append(thread)
                        stop_events.append(stop_event)
                        thread.start()
                        time.sleep(2)

                # for i, thread in enumerate(threads):
                #     thread.join(1200)  # 等待线程完成或超时
                #     if thread.is_alive():  # 检查是否超时
                #         # print(i)
                #         key = list(self.android_list.keys())[i]
                #         print(f"Task on {self.android_list[key]['Name']} 任务超时")
                #         win_log(f"{self.android_list[key]['Name']}-执行超时","error",self.android_list[key]['Name'])
                #         stop_events[i].set()  # 发送停止信号
                #         thread.join()  # 等待线程结束
                #         self.android_list[key]['status'] = 'wait'  # 重置状态

            else:
                time.sleep(5)

    def start(self, android, stop_event):
        self.set_android_status(android, 'run')
        Bytedance(android, stop_event).reset_android()
        self.set_android_status(android, 'wait')

    #
    def set_android_status(self, android, status):
        if DkGlobal().body != None:
            self.android_list[android['ip']]['status'] = status
            keys = list(self.android_list.keys())
            row = keys.index(android['ip'])
            item = QTableWidgetItem(str(status))  # 将数据转换成字符串形式
            item.setTextAlignment(Qt.AlignCenter)
            DkGlobal().body.tableWidget.setItem(row, 6, item)

    def update_table(self):
        table_data = []
        for item in self.android_list.values():
            task = item['task']
            # 这里修改统计
            table_data.append([
                item['Name'],  # 设备名称
                task['progress'] if task else '-',  # 进度
                item['ip'],  # IP
                task['app_name'] if task else '-',  # 小程序名
                item['run_count'],  # 轮次
                task['app_type'] if task else '1',  # 当前执行类型
                item['status'],  # 状态
                item['wait_time'],  # 倒计时
                item['switch']  # 开关
            ])
            if DkGlobal().body:
                DkGlobal().body.populate_table(table_data)

    def get_android_list(self):
        win_log("开始获取安卓设备.....")
        ip_item_list = IKuai().get_ip_item_list()
        # try:
        for server_ip in self.server_ips:
            print("server_ips", self.server_ips)
            # 切分ip地址
            ip = server_ip.split(':')[0]
            print(server_ip)
            http_url = "http://" + server_ip
            android_res = self.api.get("get/" + ip)
            print("android", json.loads(android_res.text))
            # JSON 转字典
            android_data = json.loads(android_res.text)
            if android_data['code'] == 200:
                win_log(f"主机{ip} 获取设备信息成功")
                for item in android_data['msg']:
                    if item['State'] != 'running':
                        continue
                    android_api_res = self.api.get(f"/get_api_info/{ip}/{item['Names']}")
                    android_api_data = json.loads(android_api_res.text)
                    if android_api_data['code'] == 200:
                        item.update(android_api_data['msg'])
                    else:
                        win_log(f"获取设备{item['ip']} 获取信息失败")
                        # 获取API报错逻辑
                        pass
                    # 最终item格式为：
                    item['SERVER_IP'] = server_ip.split(':')[0]
                    item['SERVER_PORT'] = server_ip.split(':')[1]
                    item['SERVER_HTTP'] = http_url
                    # 设备简化名
                    item['Name'] = item['Names'][35:]
                    #################################下面是自定义的字段###################
                    # 状态
                    item['status'] = 'wait'
                    # 等待时间
                    item['wait_time'] = 0
                    # 使用
                    item['switch'] = True
                    # 运行次数
                    item['run_count'] = 0
                    # 任务信息
                    item['task'] = None
                    if ip_item_list.get(item['ip']) is not None:
                        item['l2tp'] = ip_item_list[item['ip']]  # ip信息
                    else:
                        win_log(f"设备{item['Name']} 没有配置动态IP", 'error')
                        item['l2tp'] = None

                    win_log(f"获取设备{item['Name']} 获取信息成功")
                    # if item['Name'] == 'T1001':
                    self.android_list[item['ip']] = item
                    # 这里设置实例
                    self.update_table()
                return True
            else:
                # 这里写报错的逻辑
                win_log(f"主机{ip} 获取设备信息失败", 'error')
                return False

    # 保存任务
    def save_task(self):
        print("保存任务数据")
        log_file_path = os.path.join('log', 'task.json')
        print("save_task", self.android_list)
        try:
            with open(log_file_path, 'w', encoding='utf-8') as file:
                json.dump(self.android_list, file, ensure_ascii=False, indent=4)
                print("保存任务成功")
        except Exception as e:
            print("保存任务失败{e}")

    def load_task(self):
        log_file_path = os.path.join('log', 'task.json')
        try:
            with open(log_file_path, 'r', encoding='utf-8') as file:
                android_list = json.load(file)
            return android_list
        except Exception as e:
            print(f"当前没有保存的任务{e}")
            return {}

    def save_android_list_to_json(self, file_path='log/android_list.json'):
        # 确保目标目录存在
        directory = os.path.dirname(file_path)
        if not os.path.exists(directory):
            os.makedirs(directory)
        # 将self.android_list的值转换为列表，然后保存为JSON
        with open(file_path, 'w', encoding='utf-8') as f:
            json.dump(self.android_list, f, ensure_ascii=False, indent=4)
    # 读取任务
    def get_task(self):
        pass

    def set_table_item(self, android, role, item):
        if DkGlobal().body != None:
            self.app_type = item
            keys = list(self.android_list.keys())
            row = keys.index(android['ip'])
            item = QTableWidgetItem(str(item))
            item.setTextAlignment(Qt.AlignCenter)
            DkGlobal().body.tableWidget.setItem(row, role, item)

